package cn.ecut.dzy.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: java-interview
 * @description: 打印奇偶
 * @author: DingZhenYun
 * @create: 2021-10-25 12:17
 **/
class MyData {
    private int number = 1;
    private int count = 0;

    private Lock lock = new ReentrantLock();
    // 这三个相当于备用钥匙
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();

    public void print1() {
        lock.lock();
        try {
            //判断
            while (number != 1) {
                condition1.await();
            }
            //干活
            count++;

            System.out.println(Thread.currentThread().getName() + "\t " + count + "\t" );

            // 唤醒 （干完活后，需要通知B线程执行）
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print2() {
        lock.lock();
        try {
            //判断
            while (number != 2) {
                condition2.await();
            }
            //干活
            count++;
            System.out.println(Thread.currentThread().getName() + "\t " + count + "\t" );

            // 唤醒 （干完活后，需要通知B线程执行）
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}

public class Print12 {
    public static void main(String[] args) {
        MyData shareResource = new MyData();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.print1();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.print2();
            }
        }, "B").start();
    }
}
